package com.devilvan.betrice.recruitment.component;

import com.devilvan.betrice.common.BetriceCommon;
import com.devilvan.betrice.cache.BetriceRedisHelper;
import com.devilvan.betrice.recruitment.constant.BossRedisKeyConstant;
import com.devilvan.betrice.util.UEmpty;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description Boss直聘 Redis组件
 * @author Evad.Wu
 * @date 2022-08-03
 */
@Component
public class BossRedisHelper extends BetriceRedisHelper {
    public static final int PAGE_SIZE_SEPARATE = 30;

    @Resource(name = "betriceRedisTemplate")
    private RedisTemplate<String, Object> redisTemplate;

    public Map<Object, Object> generateRedisHeaderDto(BossRedisKeyConstant bossRedisKeyConstant) {
        String name = bossRedisKeyConstant.name();
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(name);
        if (UEmpty.isEmpty(entries)) {
            Map<String, String> map = new HashMap<>(2);
            map.put(BetriceCommon.SUFFIX_TOTAL_PAGE, checkRedisTotalPage(name).toString());
            map.put(BetriceCommon.SUFFIX_CURRENT_PAGE, checkRedisCurrentPage(name).toString());
            redisTemplate.opsForHash().putAll(name, map);
            entries.putAll(map);
        }
        return entries;
    }

    @Override
    public Integer checkSaveRedisTotalPage(Integer totalPg, Integer totalCount, String redisKey) {
        // 判断上游查到的Redis中的总页数 是否为初始值，若是则用第一次查询到总页数重置
        if (BetriceCommon.INIT_TOTAL_PAGE.equals(totalPg)) {
            totalPg = totalCount % PAGE_SIZE_SEPARATE == 0 ?
                    totalCount / PAGE_SIZE_SEPARATE : (totalCount / PAGE_SIZE_SEPARATE) + 1;
            redisTemplate.opsForHash().put(redisKey, BetriceCommon.SUFFIX_TOTAL_PAGE, totalPg.toString());
        }
        return totalPg;
    }

    @Override
    public String generatePageUrl(String url, Integer totalPg, Integer currentPg) {
        String pgUrl = null;
        // 如果总页数没有被初始化
        if (BetriceCommon.INIT_TOTAL_PAGE.equals(totalPg)) {
            pgUrl = url;
        } else if (currentPg <= totalPg) {
            // 有页数的情况
            pgUrl = url + "pg" + currentPg + "/";
        }
        return pgUrl;
    }

}
